#include <iostream>
#include "../Comm/Httplib.hpp"
#include "control.hpp"
#include <signal.h>

using namespace httplib;
using namespace ns_control;

static Control *cptr = nullptr;
void hander(int s)
{
    cptr->Recover();
}

int main()
{
    std::signal(SIGQUIT, hander);

    Server svr;
    Control ctrl;
    cptr = &ctrl;

    // 获取所有题目
    svr.Get("/all_questions", [&ctrl](const Request& req, Response& resp){
        std::string html;
        ctrl.AllQuestions(&html);
        resp.set_content(html, "text/html;charset=utf-8");
    });

    // 获取指定题目
    svr.Get(R"(/question/(\d+))", [&ctrl](const Request& req, Response& resp){
        std::string number = req.matches[1];
        std::string html;
        ctrl.OneQuestion(number, &html);
        resp.set_content(html, "text/html;charset=utf-8");
    });

    // 判题
    svr.Post(R"(/judge/(\d+))", [&ctrl](const Request& req, Response& resp){
        std::string number = req.matches[1];
        std::string out_json;
        ctrl.Judge(number, req.body, &out_json);
        resp.set_content(out_json, "application/json;charset=utf-8");
        // resp.set_content("判题" + number, "text/plain;charset=utf-8");
    });

    svr.set_base_dir("questions/wwwroot");
    svr.listen("0.0.0.0", 8080);
    return 0;
}